<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="门店名称">
                <a-input placeholder="请输入门店名称" v-model="queryParam.name" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="门店店长">
                <a-input placeholder="请输入门店店长名称" v-model="queryParam.manager_name" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="配送方式">
                <a-select v-model="queryParam.delivery">
                  <a-select-option value="express"> 快递 </a-select-option>
                  <a-select-option value="shop"> 门店自提 </a-select-option>
                  <a-select-option value="delivery"> 同城配送 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="运营方式">
                <a-select v-model="queryParam.is_single">
                  <a-select-option :value="0"> 非独立运营 </a-select-option>
                  <a-select-option :value="1"> 独立运营 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="门店状态">
                <a-select v-model="queryParam.open_status">
                  <a-select-option :value="0"> 打烊 </a-select-option>
                  <a-select-option :value="1"> 营业 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getShopList">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-button @click="resetQueryParams">全部门店</a-button>

        <div>
          <a-button type="primary" @click="handleEdit()" icon="plus">新建</a-button>

          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="allDelete">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        size="default"
        :columns="columns"
        :data-source="shopList"
        :customRow="customRow"
        :scroll="{ x: 'max-content' }"
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange
        }"
      >
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.cover_url" alt="" />
            </div>
            <div class="info">
              <span>{{ record.name }}</span>
              <span>{{ record.is_single == 0 ? '非独立运营' : '独立运营' }}</span>
            </div>
          </div>
        </div>
        <span slot="action" slot-scope="text, record">
          <div class="action">
            <a-button type="link" @click="handleInMd(record)" size="small">进入门店</a-button>
            <span class="line"></span>
            <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
            <span class="line"></span>
            <a-dropdown v-if="record.shop_audit == 0">
              <a class="ant-dropdown-link"> 更多 </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-popconfirm title="确认删除该门店吗？" @confirm="handleDelete(record)">
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <span
                    @click="
                      changeRow = record
                      userVisible = true
                    "
                    >更换店长</span
                  >
                </a-menu-item>
              </a-menu>
            </a-dropdown>
            <a-popconfirm title="确认删除该门店吗？" @confirm="handleDelete(record)" v-else>
              <a-button type="link" size="small">删除</a-button>
            </a-popconfirm>
          </div>
        </span>
        <div slot="contact" slot-scope="text, record">
          <div class="contact">
            <span>{{ text || '/' }}</span>
            <div class="edit">
              <a-tooltip placement="top" v-if="currentRow.id == record.id">
                <template slot="title">
                  <span>更换店长</span>
                </template>
                <a-icon
                  type="edit"
                  @click="
                    changeRow = record
                    userVisible = true
                  "
                />
              </a-tooltip>
            </div>
          </div>
        </div>
        <div slot="type" slot-scope="scope">
          {{ scope.delivery_type | type }}
        </div>
        <div slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope.open_status == 0 ? 'close' : 'open'"></span>
            <span>{{ scope.open_status == 0 ? '已打烊' : '营业中' }}</span>
          </div>
        </div>
        <div slot="address" slot-scope="scope">
          {{ scope.address }}
        </div>
        <span slot="total_profit" slot-scope="text"> ￥{{ text || 0 }} </span>
      </a-table>
    </a-card>

    <!-- 更换店长弹窗 -->
    <a-modal title="选择用户" style="width: 300px" v-model="userVisible" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search
          placeholder="输入昵称搜索"
          v-model="keyword"
          allowClear
          enter-button
          @search="$refs.table.refresh(true)"
        />
      </div>
      <s-table ref="table" rowKey="id" :columns="manager" :data="loadData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record)"> 选择 </a-button>
        </span>
      </s-table>
    </a-modal>

  </page-header-wrapper>
</template>

<script>
import storage from 'store'
import { shopList, shopDel, changeContact, batch } from '@/api/outlet'
import { generateTokenByMd } from '@/api/auth'
import { getSelectUserList } from '@/api/user'
import { STable } from '@/components'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '门店名称',
    scopedSlots: {
      customRender: 'name'
    },
    width: 200
  },
  {
    title: '配送方式',
    width: 120,
    scopedSlots: {
      customRender: 'type'
    }
  },
  {
    title: '门店佣金',
    dataIndex: 'total_profit',
    width: 120,
    scopedSlots: {
      customRender: 'total_profit'
    },
    sorter: (a, b) => a.total_profit - b.total_profit
  },
  {
    title: '店长',
    dataIndex: 'manager_name',
    width: 100,
    scopedSlots: {
      customRender: 'contact'
    }
  },
  {
    title: '手机号',
    dataIndex: 'mobile'
  },
  {
    title: '门店地址',
    width: 120,
    scopedSlots: {
      customRender: 'address'
    }
  },
  {
    title: '营业状态',
    width: 100,
    scopedSlots: {
      customRender: 'status'
    }
  },
  {
    title: '操作',
    width: 200,
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action'
    }
  }
]
const manager = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' }
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'ShopList',
  components: {
    STable
  },
  data() {
    return {
      userVisible: false,
      // 表头
      columns,
      // 店长表头
      manager,
      modalLoading: false,
      shopList: [],
      // 查询条件参数
      queryParam: {
        name: null,
        manager_name: null,
        delivery: null,
        is_single: null,
        open_status: null,
        pageNo: 1,
        pageSize: 10
      },
      // 选中行
      selectedRowKeys: [],
      // 当前鼠标经过行
      currentRow: {},
      // 点击编辑店长行
      changeRow: {},
      // 数据总条数
      totalCount: 0,
      // 选择用户数据加载
      loadData: parameter => {
        return getSelectUserList({
          ...parameter,
          storeId: storage.get('storeId'),
          type: 'user',
          keyword: this.keyword
        }).then(res => {
          return res.data
        })
      },
      // 搜索用户关键词
      keyword: ''
    }
  },
  filters: {
    type(e) {
      const type = JSON.parse(e)
      const arr = []
      if (type.length) {
        type.forEach(item => {
          if (item == 'express') {
            arr.push('快递配送')
          }
          if (item == 'shop') {
            arr.push('门店自提')
          }
          if (item == 'delivery') {
            arr.push('同城配送')
          }
        })
        return arr.join('/')
      } else {
        return '/'
      }
    }
  },
  created() {
    this.getShopList()
  },
  methods: {
    // 快速进入门店
    handleInMd(record) {
      storage.set('currentStoreUsername', this.$store.state.user.info.username)
      generateTokenByMd({ mdId: record.id })
        .then(res => {
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.set('isSaas', res.data.is_saas)
            storage.set('isSaasMd', true)
            storage.set('storeId', record.store_id)
            storage.set('mdId', record.id)
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
            storage.remove('currentStoreUsername')
          }
        })
        .catch(error => {
          storage.remove('currentStoreUsername')
          console.log(error)
        })
        .then(() => {})
    },
    handleEdit(record) {
      let url = '/outletManage/edit';
      if(record){
        url += `?id=${record.id}`;
      }
      // this.$router.push('/outletManage/edit?id=' + record.id)
      this.$router.push(url)
    },
    // 点击删除门店
    handleDelete(record) {
      const hide = this.$message.loading('删除中...', 0)
      shopDel({
        key: record.id
      }).then(res => {
        hide()
        if (res.code == 0) {
          this.$message.success('门店删除成功！')
          this.getShopList()
        } else {
          this.$error({
            content: res.msg
          })
        }
      })
    },
    // 重置查询参数
    resetQueryParams() {
      Object.assign(this.queryParam, {
        name: null,
        manager_name: null,
        delivery: null,
        is_single: null,
        open_status: null,
        pageNo: 1,
        pageSize: 10
      })
      this.getShopList()
    },
    onSelectChange(selectedRowKeys) {
      console.log(selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    // 点击批量删除
    allDelete() {
      const that = this
      const id = this.selectedRowKeys
      if (id.length) {
        this.$confirm({
          title: '是否批量删除门店?',
          async onOk() {
            const res = await batch({
              id,
              status: 1
            })
            if (res.code == 0) {
              that.resetQueryParams()
            }
          },
          onCancel() {}
        })
      }
    },
    customRow(record, index) {
      return {
        on: {
          mouseenter: () => {
            this.currentRow = record
          },
          mouseleave: () => {
            this.currentRow = {}
          }
        }
      }
    },
    // 获取门店列表
    async getShopList() {
      const hide = this.$message.loading('加载中', 0)
      const res = await shopList(this.queryParam)
      if (res.code == 0) {
        this.totalCount = res.data.totalCount
        this.shopList = res.data.data
        console.log(this.shopList)
      }
      hide()
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.pageNo = e
      this.getShopList()
    },
    // 选择店长 更换店长
    async onSelect(e) {
      const md_id = this.changeRow.id
      const saas_user_id = e.id
      const res = await changeContact({
        md_id,
        saas_user_id
      })
      if (res.code == 0) {
        this.userVisible = false
        this.getShopList()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-top: 14px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-top: 14px;
    margin-right: 20px;
  }
  .ant-btn {
    margin-top: 14px;
  }
}
.name {
  display: flex;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.contact {
  display: flex;
  align-items: center;
  .edit {
    width: 20px;
    min-width: 20px;
    cursor: pointer;
    margin-left: 5px;
  }
  .anticon:hover {
    color: #1890ff;
  }
}
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .close {
    background-color: #c6c6c6;
  }
  .open {
    background-color: #65c817;
  }
}
.action {
  display: flex;
  align-items: center;
  .line {
    width: 1px;
    height: 14px;
    background-color: #d8d8d8;
    margin-right: 8px;
  }
}
</style>
